import superagent from 'superagent';
import { message } from 'antd';
import { hashHistory } from 'dva/router'
import { baseUrl } from '../config/system';
import "babel-polyfill";

const methods = [
  'get',
  'head',
  'post',
  'put',
  'del',
  'options',
  'patch'
];

class _Api {

  constructor(opts) {

    this.opts = opts || {};

    if (!this.opts.baseURI)
      throw new Error('baseURI option is required');

    methods.forEach(method =>
      this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
        const request = superagent[method](this.opts.baseURI + path);

        if (params) {
          request.query(params);
        }
        request.set('Content-Type','application/json');
        request.withCredentials();
        if (this.opts.headers) {
          request.set(this.opts.headers);
        }

        if (data) {
          request.send(data);
        }

        request.end(function (err, body){
          if(err){
            if(err.status == 401){
              reject('尚未登录或登录信息已过期，请重新登录');
              hashHistory.push("login");
            }
            if(typeof(err.status) == "undefined"){
              reject('请求失败，请联系管理员');
            }
            if(err.status == 403){
              reject('无权限访问');
            }
            if(err.status == 404){
              reject('请求失败，请联系管理员');
            }
          }else{
            if(body.body.httpCode != 200){
              message.error(body.body.msg);
              resolve(body);
            }else{
              resolve(body);
            }
          }

        });
        //request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
      })
    );

  }

}

const api = new _Api({
  baseURI: baseUrl,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
})

export default api;
